
package nu.aing.P20140428;

/**
 * @author memekmaut@gmail.com
 */
public class SlimeXSlimonadeTycoon {

    public static void main(String[] args) {
        SlimeXSlimonadeTycoon sx = new SlimeXSlimonadeTycoon();
        final int result1 = sx.sell(new int[] { 5, 1, 1 }, new int[] { 1, 2, 3 }, 2);
    }

    public int sell(int[] morning, int[] customers, int stale_limit) {
        int result = 0;
        int[] slimonades = new int[morning.length];
        for (int i = 0; i < morning.length; i++) {
            // Early in the morning of day i:
            // All Slimonades that were produced stale_limit days ago (i.e., on
            // day i-stale_limit) go stale. You cannot sell stale Slimonades,
            // you must throw them away immediately.
            if(i - stale_limit >= 0) {
                slimonades[stale_limit - i] = 0;
            }
            
            // During day i: 
            // You can produce at most morning[i] new Slimonades. 
            // (Formally, you choose an integer X between 0 and morning[i], inclusive, and produce X Slimonades.) 
            slimonades[i] = morning[i];
            
            // Try to meet customer demands by first selling the previous days Slimonades produced
            // and then selling today's.
            for(int j = 0; j <= i; j++) {
                if(customers[i] > slimonades[j]) {
                    customers[i] = customers[i] - slimonades[j];
                    result = result + slimonades[j];
                    slimonades[j] = 0;
                }
                else {
                    slimonades[j] = slimonades[j] - customers[i];
                    result = result + customers[i];
                    customers[i] = 0;
                }
                if(customers[i] <= 0) {
                    break;
                }
            }
        }

        return result;
    }
}
